package com.woniuxy.shiro;

import com.woniuxy.domain.Permission;
import com.woniuxy.dto.DtoJSONResultCode;
import com.woniuxy.exception.TokenException;
import com.woniuxy.service.PermissionService;
import lombok.SneakyThrows;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @ClassName Realm
 * @Description JWT领域类
 * @Author 王维鑫
 * @Date 2021/5/13 0013 10:31
 * @Version 1.0
 */
public class JWTRealm extends AuthorizingRealm {
    @Autowired
    private PermissionService permissionService;
    @Override
    /**
     *@Author 王维鑫
     *@Description 判定token类型，如果是JWTToken则允许执行认证
     *@Param [token]
     *@return boolean
     **/
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //取出token
        String token= (String) principalCollection.getPrimaryPrincipal();
        //使用JWTUtils解析并获取subject
        String id = null;
        SimpleAuthorizationInfo info=null;
        System.out.println("授权");
        try {
            id = JWTUtils.getId(token);
            System.out.println("1231231231231231231231231231"+id);
            int userId = Integer.parseInt(id);
            List<Permission> permissions = permissionService.selectPermissionByUserIdNo(userId);
            //模拟查询数据库权限
            info= new SimpleAuthorizationInfo();
            for (Permission permission : permissions) {
                info.addStringPermission(permission.getPermissionName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return info;
    }





    /**
     *@Author 王维鑫
     *@Description 校验token方法，返回认证信息
     *@Param [authenticationToken]
     *@return org.apache.shiro.authc.AuthenticationInfo
     **/
    @SneakyThrows
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String token= (String) authenticationToken.getPrincipal();
        //进行token校验
        //通过校验说明token有效 返回认证信息
        try {
            JWTUtils.validateJWT(token);
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(token, token,getName());
            return info;
        } catch (Exception e) {
            //没有通过校验抛Token错误异常
            e.printStackTrace();
            throw new TokenException(DtoJSONResultCode.TOKENERROR.getCode(), DtoJSONResultCode.TOKENERROR.getMessage());
        }
    }
}
